<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script>
        
        let list = [
            {id:'1', pid:'',name:'小王'},
            {id:'2', pid:'',name:'小刘'},
            {id:'3', pid:'1',name:'小张'},
            {id:'4', pid:'1',name:'小赵'},
            {id:'5', pid:'2',name:'小钱'},
            {id:'6', pid:'3',name:'小钱'}
        ]

        list = getTree(list,'')

        function  getTree(arr) {
            const arr1 = {} 
            const newArr= []
            //遍历数组  没有children的添加children属性
            arr.forEach(item =>{
                if(!item.children) {
                    item.children = []
                }
                arr1[item.id]=item
            })

            //再次遍历数组
            arr.forEach(item => {
                
                //如果pid不为'' 就把其加入到id为其pid的children中
                //因为子级的pid等于父级的id 所以arr1[父级id]与arr1[子级pid]===
                //如果pid为'' 就说明是最上级 直接push进新数组
                if(item.pid) {
                    arr1[item.pid].children.push(item)
                } else {
                    newArr.push(item)
               }
            })
           return newArr
        }

        console.log(list)
    </script>
</body>
</html>